<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="../../static/lib/vue/vue3.1.1.js"></script>
    <style>

    </style>
</head>
<body>

<div id="app">
    <p style="font-size:25px;">计数器: {{ counter }}</p>
    <button @click="counter++" style="font-size: 25px;">点我</button>
    <br>

    <p>
        千米 : <input type="text" v-model="kilometers">
        米 : <input type="text" v-model="meters"></p>
    <p id="info"></p>

    <div id="watch-example">
        <p>
            输入一个问题，以 ? 号结尾输出答案:
            <input v-model="question"/>
        </p>
        <p>{{ answer }}</p>
        <img :src="imgUrl" alt="">
    </div>
</div>


<script>

    const app = Vue.createApp({
        data() {
            return {
                counter: 1,
                kilometers: 0,
                meters: 0,
                question: '',
                answer: '每个问题结尾需要输入 ? 号。',
                imhUrl: ''
            }
        },
        watch: {
            kilometers: function (val) {
                this.kilometers = val;
                this.meters = this.kilometers * 1000
            },
            meters: function (val) {
                this.kilometers = val / 1000;
                this.meters = val;
            },
            // 每当问题改变时，此功能将运行，以 ? 号结尾
            question(newQuestion, oldQuestion) {
                if (newQuestion.indexOf('?') > -1) {
                    this.getAnswer()
                }
            },
        },
        methods: {
            getAnswer() {
                this.answer = '加载中...'
                axios
                    .get('https://yesno.wtf/api')
                    .then(response => {
                        this.answer = response.data.answer;
                        this.imgUrl = response.data.image;
                    })
                    .catch(error => {
                        this.answer = '错误! 无法访问 API。 ' + error
                    })
            }
        }
    }).mount('#app')

    app.$watch('counter', function (nval, oval) {
        alert('计数器值的变化：' + oval + '编为：' + nval + '!')
    })
    app.$watch('kilometers', function (newValue, oldValue) {
        // 这个回调将在 vm.kilometers 改变后调用
        document.getElementById("info").innerHTML = "修改前值为: " + oldValue + "，修改后值为: " + newValue;
    })
</script>
</body>
</html>